// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Q [author] rhyme_lph
// J [email]  rhymelph@gmail.com
// l [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/company_entity.dart';
import 'package:finance_app/src/entities/company_financial_year_entity.dart';
import 'package:finance_app/src/provider/setting/company_profile_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/add_form.dart';
import 'package:finance_app/src/widgets/form/phone_number_input_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:finance_app/src/widgets/input/input_name_field.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/list_item/setting_list_item.dart';
import 'package:finance_app/src/widgets/select/normal_check_box.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

export 'package:finance_app/src/entities/company_entity.dart';

@RouterMeta(paramName: "companyProfilePage")
class CompanyProfilePage extends StatefulWidget {
  final CompanyEntity data;

  const CompanyProfilePage({Key key, this.data}) : super(key: key);

  @override
  _CompanyProfilePageState createState() => _CompanyProfilePageState();
}

class _CompanyProfilePageState extends State<CompanyProfilePage>
    with PagePresenter<CompanyProfilePage, CompanyProfileProvider> {
  @override
  void initState() {
    provider.initDate(Config.currentCompany);
    super.initState();
  }

  @override
  PreferredSizeWidget get appBar =>
      getDefaultAppBar(title: S.current.company_settings, actions: [
        NormalSaveTextButton(
          onTap: provider.onSave,
        )
      ]);

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            _buildBusinessInfoItem(),
            AppSpaces.h20,
            ListHeaderItem(
              title: S.current.company_details,
            ),
            FromInputField(
              controller: provider.uenController,
              focusNode: provider.uenFocusNode,
              tip: S.current.uen,
            ),
            listBuilder<String>(
              selector: (_, __) => __.businessType?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.business_type,
                value: value,
                onTap: provider.onChangeBusinessType,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.industry?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.industry,
                value: value,
                onTap: provider.onChangeIndustry,
                border: null,
              ),
            ),
            ListHeaderItem(
              title: S.current.business_settings,
            ),

            listBuilder<List<CompanyFinancialYearEntity>>(
              selector: (_, __) => __?.financialYears,
              builder: (BuildContext context,
                  List<CompanyFinancialYearEntity> value, Widget child) {
                CompanyFinancialYearEntity selected;
                if (value.length > 0)
                  selected = value.firstWhere((element) => element.status == 1,
                      orElse: () => value.last);
                if (value.length == 0) return Container();
                return Visibility(
                  visible: value.length > 1,
                  child: ValueSelectForm(
                    title: S.current.switch_financial_year,
                    value: selected != null
                        ? selected.isCurrentYear
                            ? S.current.current_financial_year
                            : DateTimeUtils.formatFinancialYearDate(
                                selected.startDate, selected.endDate)
                        : null,
                    onTap: provider.onChangeFinancialYear,
                    trailing: PressedOpacityButton(
                      onPressed: provider.onShowInfo,
                      padding: EdgeInsets.only(right: getDp(10)),
                      child: SvgPicture.asset(
                        A.assetsImagesStyleInformation_1,
                        width: getDp(24),
                        height: getDp(24),
                        fit: BoxFit.contain,
                        color: aceBlueColor,
                      ),
                    ),
                  ),
                  replacement: Column(
                    children: [
                      listBuilder<DateTime>(
                        selector: (_, __) => __.startDate,
                        builder: (BuildContext context, DateTime value,
                                Widget child) =>
                            ValueSelectForm(
                          title: S.current.financial_year_start_date,
                          value: DateTimeUtils.formatGlobalDateTime(value),
                          onTap: provider.onChangeStartDate,
                        ),
                      ),
                      listBuilder<DateTime>(
                        selector: (_, __) => __.endDate,
                        builder: (BuildContext context, DateTime value,
                                Widget child) =>
                            ValueSelectForm(
                          title: S.current.financial_year_end_date,
                          value: DateTimeUtils.formatGlobalDateTime(value),
                          border: null,
                          onTap: provider.onChangeEndDate,
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
            // FromInputField(
            //   controller: provider.nextMonthController,
            //   focusNode: provider.nextMonthFocusNode,
            //   keyboardType: TextInputType.number,
            //   border: null,
            //   inputFormatterList: [
            //     intInputFormatter,
            //   ],
            //   tip: S.current.next_financial_period_months,
            // ),
            ListHeaderItem(
              title: S.current.contact_details,
            ),
            FromInputField(
              controller: provider.emailController,
              focusNode: provider.emailFocusNode,
              keyboardType: TextInputType.emailAddress,
              tip: S.current.email,
            ),
            PhoneNumberInputForm(
              controller: provider.phoneNumberController,
              focusNode: provider.phoneNumberFocusNode,
              countryCodeCallback: provider.updateCountryCode,
              defaultCountryCode: provider.countryCode,
            ),
            FromInputField(
              controller: provider.websiteController,
              focusNode: provider.websiteFocusNode,
              tip: S.current.website,
            ),
            listBuilder<String>(
              selector: (_, __) => __.address,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.address,
                value: value,
                onTap: provider.onChangeAddress,
              ),
            ),
            FromInputField(
              controller: provider.unitNumberController,
              focusNode: provider.unitNumberFocusNode,
              tip: S.current.unit_number,
            ),
            FromInputField(
              controller: provider.postalCodeController,
              focusNode: provider.postalCodeFocusNode,
              tip: S.current.postal_code,
            ),
            listBuilder<bool>(
              selector: (_, __) => __.isShowDeliveryAddress,
              builder: (BuildContext context, bool value, Widget child) =>
                  AnimatedCrossFade(
                      firstChild: AddForm(
                        title: S.current.add_delivery_address,
                        onTap: provider.onAddDeliveryAddress,
                      ),
                      secondChild: Column(
                        children: [
                          ListHeaderItem(
                            title: S.current.delivery_address,
                          ),
                          listBuilder<String>(
                            selector: (_, __) => __.deliveryAddress,
                            builder: (BuildContext context, String value,
                                    Widget child) =>
                                ValueSelectForm(
                              title: S.current.delivery_address,
                              value: value,
                              onTap: provider.onChangeDeliveryAddress,
                            ),
                          ),
                          FromInputField(
                            controller: provider.deliverUnitNumberController,
                            focusNode: provider.deliverUnitNumberFocusNode,
                            tip: S.current.unit_number,
                          ),
                          FromInputField(
                            controller: provider.deliverPostalCodeController,
                            focusNode: provider.deliverPostalCodeFocusNode,
                            tip: S.current.postal_code,
                          ),
                        ],
                      ),
                      crossFadeState: value == false
                          ? CrossFadeState.showFirst
                          : CrossFadeState.showSecond,
                      duration: Duration(milliseconds: 500)),
            ),
            ListHeaderItem(
              title: S.current.default_settings,
            ),

            rootListBuilder<String>(
              selector: (_, __) => Config.settingInfo?.currencyCode?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.currency,
                onTap: provider.onChangeCurrency,
                value: value,
                border: null,
              ),
            ),
            // rootListBuilder<String>(
            //   selector: (_, __) => Config.settingInfo?.paymentType?.name,
            //   builder: (BuildContext context, String value, Widget child) =>
            //       ValueSelectForm(
            //     title: S.current.payment_method,
            //     onTap: provider.onChangePaymentType,
            //     value: value,
            //   ),
            // ),
            // rootListBuilder<String>(
            //   selector: (_, __) => Config.paymentTerm?.name,
            //   builder: (BuildContext context, String value, Widget child) =>
            //       ValueSelectForm(
            //     title: 'Payment Term',
            //     onTap: provider.onChangePaymentTerm,
            //     value: value,
            //   ),
            // ),
            // rootListBuilder<String>(
            //   selector: (_, __) => Config.settingInfo?.taxData?.displayName,
            //   builder: (BuildContext context, String value, Widget child) =>
            //       ValueSelectForm(
            //     title: S.current.tax_type,
            //     onTap: provider.onChangeTaxType,
            //     value: value,
            //     border: null,
            //   ),
            // ),
            ListHeaderItem(
              title: S.current.format_style,
            ),
            rootListBuilder<String>(
              selector: (_, __) => Config.settingInfo?.dateFormat,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.date_format,
                onTap: provider.onChangeDateFormat,
                value: value.toUpperCase(),
              ),
            ),
            SettingListItem(
              title: S.current.number_format,
              onTap: provider.onNumberFormat,
            ),
            SettingListItem(
              title: S.current.template_style,
              onTap: provider.onTemplateStyle,
              border: null,
            ),
            ListHeaderItem(
              title: S.current.custom_fields,
            ),
            SettingListItem(
              title: S.current.unit_of_measurement,
              onTap: provider.onUnitOfMeasurement,
              border: null,
            ),
            ListHeaderItem(
              title: S.current.alert_settings,
            ),
            ListHeaderItem(
              hasBackgroundColor: false,
              title: S.current.send_notification_when,
            ),
            rootListBuilder<List<String>>(
              selector: (_, __) => List.from(Config.settingInfo.alerts),
              builder:
                  (BuildContext context, List<String> value, Widget child) =>
                      Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: Config.settingData.alerts
                    .map((e) => PressedOpacityButton(
                          onPressed: () => provider.onCheckAlertSetting(e),
                          child: NormalFormWrapper(
                            bottomPadding: getDp(10),
                            topPadding: getDp(10),
                            child: listBuilder<bool>(
                              selector: (_, __) => value.contains(e.key),
                              builder: (BuildContext context, bool value,
                                      Widget child) =>
                                  NormalCheckBox(
                                title: e.name,
                                isSelect: value,
                              ),
                            ),
                          ),
                        ))
                    .toList(),
              ),
            ),
            AppSpaces.h30,
          ],
        ),
      );

  Widget _buildBusinessInfoItem() {
    return NormalFormWrapper(
      leftPadding: getDp(25),
      topPadding: getDp(19),
      bottomPadding: getDp(0),
      rightPadding: getDp(20),
      child: Row(
        children: [
          listBuilder<String>(
            selector: (_, __) => __.networkPath,
            builder: (BuildContext context, String avatar, Widget child) =>
                listBuilder<String>(
              selector: (_, __) => __.imagePath,
              builder: (BuildContext context, String value, Widget child) =>
                  PressedOpacityButton(
                onPressed: provider.onUpdateLoadAvatar,
                child: CircleAvatar(
                  backgroundColor: aceWhiteGreyColor,
                  backgroundImage: Config.networkToLocalProvider(avatar, value),
                  radius: getDp(34.5),
                  child: avatar == null && value == null
                      ? SvgPicture.asset(
                          A.assetsImagesStylePhoto_camera_interface_symbol_for_button_2,
                          width: getDp(28),
                          height: getDp(28),
                        )
                      : null,
                ),
              ),
            ),
          ),
          SizedBox(
            width: getDp(15),
          ),
          Expanded(
            child: InputBoxShadowField(
              controller: provider.businessNameController,
              focusNode: provider.businessNameFocusNode,
              tip: S.current.business_name,
            ),
          ),
        ],
      ),
    );
  }
}
